package org.lanyu.springainovel.common.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

/**
 * WebSocket配置类
 * 统一管理所有WebSocket连接端点和消息代理配置
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 配置消息代理，支持统一任务主题
        config.enableSimpleBroker("/topic");
        // 设置应用目标前缀
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 统一WebSocket端点，支持所有异步任务
        registry.addEndpoint("/ws-unified")
                .setAllowedOriginPatterns("*")
                .setHandshakeHandler(new CustomHandshakeHandler())
                .withSockJS();
    }
    
    /**
     * 自定义握手处理器，用于处理SockJS连接
     */
    private static class CustomHandshakeHandler extends DefaultHandshakeHandler {
        @Override
        protected boolean isValidOrigin(ServerHttpRequest request) {
            // 允许所有来源，便于开发环境测试
            return true;
        }
    }
}
